<template>
	<view>
		<view class="new-address-area">
			<view>
				<text>收件人姓名：</text>
				<input type="text" placeholder="收件人姓名" v-model="newAddressObj.username">
			</view>
			<view>
				<text>收件人号码</text>
				<input type="text" placeholder="收件人号码" v-model="newAddressObj.userTel">
			</view>
			<view>
				<text>省市区选择</text>
				<picker mode="region" :value="newAddressObj.userAddress" @change="bindRegionChange">
				    <view class="picker">
				      当前选择：{{newAddressObj.userAddress[0]}}，{{newAddressObj.userAddress[1]}}，{{newAddressObj.userAddress[2]}}
				    </view>
				  </picker>
			</view>
			<view>
				<text>详细地址</text>
				<input type="text" placeholder="详细地址" v-model="detailAddress">
			</view>
			<view class="btn-area">
				<button type="default" @click="cancel">取消</button>
				<button type="primary" @click="addNewInfo">确定</button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 统计用户输入的收货信息对象
				newAddressObj: {
					username: '',
					userTel: '',
					userAddress: ['北京市', '北京市', '东城区']
				},
				// 详细住址
				detailAddress: ''
			}
		},
		methods: {
			// 将用户填写的新的收货地址信息对象表单提交至数据库
			async addToAddressList() {
				const { data: res } = await uni.$http.post('/address/add', {
					name: this.newAddressObj.username,
					tel: this.newAddressObj.userTel,
					address: this.newAddressObj.userAddress + this.detailAddress,
					id: uni.getStorageSync('uid')
				})
				if(res.meta.status !== 200) return uni.showToast({
					title: res.meta.message,
					icon: 'error',
					duration: 1500
				})
				uni.showToast({
					title: res.meta.message,
					icon: 'success',
					duration: 1000
				})
			},
			// 取消按钮被点击时触发
			cancel() {
				this.resetForm()
				uni.navigateBack()
			},
			// 确定按钮被点击时触发
			addNewInfo() {
				this.addToAddressList()
				this.resetForm()
				uni.navigateBack()
			},
			// picker 采集框数据发生变化时触发
			bindRegionChange(e) {
				this.newAddressObj.userAddress = e.detail.value
			},
			resetForm() {
				this.newAddressObj = {
					username: '',
					userTel: '',
					userAddress: ['北京市', '北京市', '东城区'],
					infoState: false
				}
				this.detailAddress = ''
			}
		}
	}
</script>

<style>
	.new-address-area {
		padding: 40rpx;
	}
	
	.new-address-area input,
	.picker{
		width: 90%;
		border: 1px solid #ccc;
		border-radius: 30rpx;
		padding: 20rpx;
		margin: 20rpx auto;
	}

	.btn-area {
		display: flex;
		justify-content: space-around;
		margin-top: 40rpx;
	}
	
	.btn-area button {
		width: 30%;
	}
	
	.show-address-area button {
		width: 280rpx;
		margin-top: 30rpx;
	}
</style>
